package com.chap7;

import java.util.concurrent.locks.ReentrantLock;

/**
 * <p>
 * <code>ReentrantLockDemo</code>
 * </p>
 *
 * @author junbao3
 * TODO
 * @date 2023-03-16 14:38
 * Copyright (C) 2021 IFlyTek. All rights reserved.
 */
public class ReentrantLockDemo {
    private final MyLock lock = new MyLock();
    private static int tickets = 8;

    public void buyTicket(){
        lock.lock();

        try{
            if (tickets>0){
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+"购买了第"+tickets-- +"张票");
                //一个线程可以买多张票
                buyTicket();
            }else {
                System.out.println("票已经卖完了，"+Thread.currentThread().getName()+"抢票失败");
            }

        }finally {
            lock.unLock();
        }
    }

    public static void main(String[] args) {
        ReentrantLockDemo ticketSystem = new ReentrantLockDemo();
        for (int i = 1; i <=10 ; i++) {
            Thread thread = new Thread(()->{
                ticketSystem.buyTicket();
            },"线程"+i);
            thread.start();
        }

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("剩余票数：" + tickets);

    }
}
